package Offer.offer;

import domain.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 二叉树的深度
 * Created by 雷文康 on 2018/1/4.
 */
public class Test39a二叉树的深度 {

    //递归
    public static int treeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = treeDepth(root.left);
        int right = treeDepth(root.right);
        return left > right ? (left + 1) : (right + 1);
    }

    //非递归
    public static int treeDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }

        List<TreeNode> list = new ArrayList<>();
        list.add(root);
        int depth = 0;
        while (!list.isEmpty()){
            depth++;
            List<TreeNode> layerList = new ArrayList<>();
            for(int i = 0; i < list.size(); i++) {
                TreeNode node = list.get(i);
                if (node.left != null) {
                    layerList.add(node.left);
                }
                if (node.right != null) {
                    layerList.add(node.right);
                }
            }
            list = layerList;
        }
        return depth;

    }

}
